package models

import (
	"errors"
	"fmt"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"hc_server/routers/response/merchantResponse"
)

// MerchantSettlementRate 商户结算费率
type MerchantSettlementRate struct {
	Model
	MerchantId       int     `json:"merchant_id" gorm:"comment:'商户id'"`
	D0Rate           float64 `json:"d0_rate" gorm:"type:decimal(10,6);comment:'D0付款费率'"`
	D0Charge         float64 `json:"d0_charge" gorm:"type:decimal(10,6);comment:'D0付款手续费'"`
	D1Rate           float64 `json:"d1_rate" gorm:"type:decimal(10,6);comment:'D1付款费率'"`
	D1Charge         float64 `json:"d1_charge" gorm:"type:decimal(10,6);comment:'D1付款手续费'"`
	WithdrawalRate   string  `json:"withdrawal_rate" gorm:"comment:'提现费率'"`
	WithdrawalCharge string  `json:"withdrawal_charge" gorm:"comment:'提现手续费'"`
}

// MerchantSettlementRateExistByID 通过id判断是否存在
func MerchantSettlementRateExistByID(id int) (bool, error) {
	var mer MerchantSettlementRate
	err := db.Select("id").Where("id = ?", id).First(&mer).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.WithError(err).Errorf("此代理不存在: id:%d err:%v", id, err)
		return false, fmt.Errorf("此代理不存在")
	}

	return mer.ID > 0, nil
}

// MerchantSettlementRateInfoByMerchantId 通过MerchantId获取数据
func MerchantSettlementRateInfoByMerchantId(merchantId int) (*merchantResponse.GetMerchantSettlementRateInfoResponse, error) {
	var mer *merchantResponse.GetMerchantSettlementRateInfoResponse
	err := db.Model(MerchantSettlementRate{MerchantId: merchantId}).First(&mer).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.WithError(err).Errorf("此商户费率不存在: id:%d err:%v", merchantId, err)
		return nil, fmt.Errorf("此商户费率不存在")
	}

	return mer, nil
}
